###############################################################################
#                                                                             #
#    This file is part of the "ssbot" Python module.                          #
#    It is distributed under the MIT License. See LICENSE.txt for details.    #
#                                                                             #
###############################################################################

import os
import re
import subprocess


""" The size of history to save or display in any context of the ssbot module.

It is a "one size fits all" value. Setting it to a different value before
using other constructs in the ssbot module will change the size of history.
"""
HISTORY_LENGTH = 50

BUILD_INTERVAL = 10

STATUS_RUNNING = 'Running'
STATUS_COMPLETED = 'Completed'
STATUS_PENDING = 'Pending'

RESULT_PASS = 'Pass'
RESULT_FAIL = 'Fail'
RESULT_EXCEPTION = 'Exception'


def run_cmd(args, cwd=None, message=None):
    """ Runs the command in the list ARGS and returns the stdout as a string.

    RunTimeError is raised if the command fails.
    """
    p = subprocess.Popen(
        args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd)
    p.wait()
    if p.returncode:
        raise RuntimeError("%s\n%s" % (message, p.stderr))
    return [l.strip() for l in p.stdout.readlines()]


def validate_name(name):
    """ Validate NAME.

    Schedulers and builders have a name which needs be in a particular format.
    This function checks if the names are in that format. The name can be of
    any length > 0 and can contain any of the following:

    1. Lower case characters a-z
    2. Upper case characters A-Z
    3. Digits 0-9
    4. The '_' character
    """
    name_regex = re.compile('^[a-zA-Z0-9_]+$')
    if not name_regex.match(name):
        raise ValueError('Invalid name "%s". '
                         'Name should match the regex ^[a-zA-Z0-9_]+$' % name)


def to_int(value):
    """ Convert VALUE to an integer if possible.

    Returns a tuple (<integer>, <boolean>). The boolean value if True if it is
    possible to convert VALUE to an integer. In which case the <integer> is the
    number got from converting VALUE to an integer. Otherwise, the boolean
    value is False and the integer 0.
    """
    try:
        int_val = int(value)
        return (int_val, True)
    except ValueError:
        return (0, False)
